package com.xieshue.im.server;

import com.xieshue.im.handler.codec.ImMessageDecoder;
import com.xieshue.im.handler.codec.ImMessageEncoder;
import com.xieshue.im.server.handler.ImServerChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IM server 启动类
 *
 * @author xieshue
 * @date 2017\12\11 0011
 */
public class ImServerBootstrap {

    private static final Logger logger = LoggerFactory.getLogger(ImServerBootstrap.class);

    private final String host;
    private final int port;

    public ImServerBootstrap(int port) {
        this("127.0.0.1", port);
    }

    public ImServerBootstrap(String host, int port) {
        if (logger.isDebugEnabled()) {
            logger.info("启动netty服务...");
        }
        this.host = host;
        this.port = port;
    }

    public void server() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup worksGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, worksGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("encoder", new ImMessageEncoder());
                            ch.pipeline().addLast("decoder", new ImMessageDecoder());
                            ch.pipeline().addLast(new ImServerChannelHandler());
                            ch.pipeline().addLast(new IdleStateHandler(5, 0, 0));
                        }
                    });
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println(future.channel().id());
            if (logger.isDebugEnabled()) {
                logger.info("启动netty服务成功...");
            }
            future.channel().closeFuture().sync();
        } finally {
            if (logger.isDebugEnabled()) {
                logger.info("关闭netty服务...");
            }
            bossGroup.shutdownGracefully();
            worksGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        try {
            new ImServerBootstrap(8081).server();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
